package de.hs_mannheim.visualscheduler.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 * The Class NavigationBar provides an internal page value along with next and previous buttons.
 */
public class NavigationBar extends JPanel implements ActionListener {
	
	/**
	 * An asynchronous update interface for receiving notifications about NavigationBar information as the NavigationBar is
	 * constructed.
	 */
	public interface NavigationBarObserver {
		void setPage(int page);
	}

	private static final long						serialVersionUID	= -4228925015179842888L;

	private final JButton							buttonNext			= new JButton("Next");
	private final JButton							buttonPrev			= new JButton("Previous");
	private final int								maxPage;
	private int										page;
	private final ArrayList<NavigationBarObserver>	observers			= new ArrayList<NavigationBarObserver>();

	/**
	 * Instantiates a new navigation bar.
	 * 
	 * @param maxPage
	 *            allowed
	 */
	public NavigationBar(final int maxPage) {
		super(new BorderLayout());
		this.maxPage = maxPage;
		//buttonNext.setPreferredSize(new Dimension(75, 20));
		add(buttonNext, BorderLayout.EAST);
		add(buttonPrev, BorderLayout.WEST);
		buttonPrev.setEnabled(false);

		buttonNext.addActionListener(this);
		buttonPrev.addActionListener(this);
	}


	@Override
	public void actionPerformed(final ActionEvent arg0) {
		if (buttonNext == arg0.getSource()) {
			if (page < maxPage - 1) {
				page++;
				notifyObservers();
			}
		} else if (buttonPrev == arg0.getSource()) {
			if (page > 0) {
				page--;
				notifyObservers();
			}
		}
		
		// Disable Next Button on last page 
		if (page < maxPage - 1) {
			buttonNext.setEnabled(true);
		} else {
			buttonNext.setEnabled(false);
		}

		// Disable Previous Button on first page 
		if (page > 0) {
			buttonPrev.setEnabled(true);
		} else {
			buttonPrev.setEnabled(false);
		}
	}

	/**
	 * Adds a observer to the Bar. It will be called everytime the internal page changed
	 * as a result of the User pressing next or previous
	 * 
	 * @param observer
	 *            to notify on changes
	 */
	public void addObserver(final NavigationBarObserver observer) {
		observers.add(observer);
	}

	/**
	 * Notifies all registered observers of the new current page.
	 */
	protected void notifyObservers() {
		for (final NavigationBarObserver obs : observers) {
			obs.setPage(page);
		}
	}
}
